package org.ns.longhttp.selector.datamapper.responseid;

import sun.misc.Unsafe;

import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

public class DefaultDataResponseIdService implements DataResponseIdService {
    private static final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
    private AtomicLong count = new AtomicLong();
    private long startTime = 1577808000000L; // 1577808000000 = 2020-00-00 00:00:00
    public static long getInitId() {
        return (System.currentTimeMillis() - 1577808000000L) / 1000 * 1000000;
    }

    @Override
    public Long getId() {
        try {
            long initId = getInitId();
            if (initId > count.get()) {
                while (!atomicBoolean.compareAndSet(false, true)) ;
                if (initId > count.get()) {
                    count.set(initId + 1);
                    return initId + 1;
                }
            }
        } finally {
            atomicBoolean.set(false);
        }
        return  count.incrementAndGet();
    }

    @Override
    public Long getMaxId() {
        return count.get();
    }

    public static void main(String[] args) throws Exception{
      //DefaultDataResponseIdService service = new DefaultDataResponseIdService();
        //for (int i = 0; i < 100000; i++) {
            //service.getId();

        //System.out.println( service.getId());
//        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        System.out.println(sdf.parse("2020").getTime());
        System.out.println();
        System.out.println(getInitId());
        System.out.println(Long.MAX_VALUE);
    }
}
